import { currentUser as queryCurrentUser } from '@/api/user';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';

import Footer from '@/components/Footer';

const loginPath = '/user/login';

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: any;
  currentUser?: any;
  loading?: boolean;
  fetchUserInfo?: () => Promise<any>;
}> {
  const fetchUserInfo = async (data = { userId: '' }) => {
    try {
      const msg = await queryCurrentUser({ userId: data.userId });
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果不是登录页面，执行
  const { location } = history;
  if (location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      // settings: defaultSettings as Partial<LayoutSettings>,
    };
  }
  return {
    fetchUserInfo,
    // settings: defaultSettings as Partial<LayoutSettings>,
  };
}

// ,setInitialState
export const layout: RunTimeLayoutConfig = ({
  initialState,
}: Record<string, any>) => {
  return {
    // logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    // menu: {
    //   locale: false,
    // },
    menuHeaderRender: undefined,
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      const val = localStorage.getItem('currentUser');
      const { currentUser } = val ? JSON.parse(val) : { currentUser: null };
      if (
        !initialState?.currentUser &&
        location.pathname !== loginPath &&
        !currentUser
      ) {
        history.push(loginPath);
      }
    },
  };
};
// export const request: RequestConfig = {
//     timeout: 1000,
//     errorConfig: {
//         errorHandler() {
//         },
//         errorThrower() {
//         }
//     },
//     requestInterceptors: [
//         (config: any) => {
//             return config;
//         },
//         (error: any) => {
//             return error;
//         },
//     ],
//     responseInterceptors: [
//         (response: any) => {
//             return response;
//         }
//     ]
// }
